import { superviseInfoAPI } from "@api/superviseInfo";
import historyList from "@/views/superviseInfo/components/historyList";
import { mapState } from "vuex";
import state from "@/tools/state";
import { mapTable } from "@/tools/util";

export const mixin = {
  data() {
    return {
      selectData: [],
      formData: {}
    }
  },
  computed: {
    ...mapState('sasspWeb', state),
    btnDisabled() {
      return false
      // return !this.selectData.length
    },
    ...mapState('user', {
      currentUserId: (state) => state.currentSysInfo.id,
      currentRole: (state) => state.currentSysInfo.userPurview ? state.currentSysInfo.userPurview.userType : ''
    }),
    showCurrentBtn() {
      const roleList = ['1', '3', '5', '10']
      // const roleList = ['5']
      return this.currentRole.split(',').some(item => roleList.includes(item))
    }
  },
  mounted() {
    this.formData = this.searchData
  },
  methods: {
    searchHandle() {
      const params = {};
      this.formData.forEach(item => {
        if (item.hasOwnProperty('aliasField')) {
          params[item.aliasField] = item[item.aliasField] ? item[item.aliasField] : 0
        } else {
          params[item.field] = item.value;
        }
      });
      this.$refs.listTable.load(params);
    },
    resetHandle() {
      this.formData.forEach(item => {
        if (item.field === 'resultState') {
          item.value = []
        } else {
          item.value = "";
        }
      });
      this.$refs.listTable.load(this.pageTableConfig.initParam);
    },
    excelHandle(res) {
      const excelName = decodeURI(res.headers["content-disposition"].split(";")[1].split("=")[1]);
      const a = document.createElement("a");
      const blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" });
      a.href = URL.createObjectURL(blob);
      a.style.display = "none";
      a.download = excelName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    importHandle() {
      this.$refs.selectFile.click()
    },
    readWareHandle() {
      superviseInfoAPI.toRead({ ids: this.selectData }, mapTable[location.hash.substring(2)].path).then(res => {
        this.$message.success('操作成功')
        this.searchHandle()
      })
    },
    checkFileType: function(fileType) {
      const acceptTypes = ["xls", "xlsx"];
      for (let i = 0; i < acceptTypes.length; i++) {
        if (fileType === acceptTypes[i]) {
          return true;
        }
      }
      return false;
    },
    importData(e, url) {
      const inputCom = e.target;
      const files = inputCom.files;
      let param = new FormData();
      [].forEach.call(files, file => {
        if (!this.checkFileType(file.name.split(".").pop())) {
          this.$message.error({
            content: "仅支持导入 excel 文件",
            duration: 3
          });
          return false;
        } else {
          param.append("file", file);
        }
      });

      this.showUploading();
      e.target.value = ''
      superviseInfoAPI.importExcel(param, url).then(res => {
        this.$message.success('导入成功')
        this.hideUploading();
        this.searchHandle()
      }).catch((err) => {
        console.error(err)
        this.hideUploading();
      })
    },
    hideUploading() {
      this.$Spin.hide();
    },
    selectHandle(data) {
      this.selectData = data.map(item => item.id)
    },
    exportHandle(path) {
      const params = {};
      this.formData.forEach(item => {
        if (item.hasOwnProperty('aliasField')) {
          params[item.aliasField] = item[item.aliasField] ? item[item.aliasField] : 0
        } else {
          params[item.field] = item.value;
        }
      });
      this.$Spin.show()
      superviseInfoAPI.dataExport({ ids: this.selectData, ...params }, path).then(res => {
        this.excelHandle(res)
        this.$Spin.hide()
      })
    },
    downHandle(type) {
      superviseInfoAPI.downloadBatch({ type: type }).then(res => {
        const excelName = decodeURI(res.headers["content-disposition"].split(";")[1].split("=")[1]);
        const a = document.createElement("a");
        const blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" });
        a.href = URL.createObjectURL(blob);
        a.style.display = "none";
        const nameMap = {
          'purchase-info': '采购信息',
          'subject-info': '标的信息',
          'offer-supplier': '报价供应商',
          'contract-info': '合同信息',
          'buyer-info': '买方信息',
          'seller-info': '卖方信息',
          'performance-info': '履约信息',
          'invoice-payment': '发票付款'
        }
        a.download = nameMap[this.$route.name] + '-' + excelName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      })
    },
    selectUpload(allReport, path) {
      // if (!this.selectData.length && !allReport) {
      //   return this.$Message.warning('请选择数据')
      // }
      const params = {
        ids: this.selectData,
        allReport: allReport
      }
      superviseInfoAPI.postReport(params, path).then(res => {
        this.$message.success('操作成功')
        this.selectData = []
        this.pageTableConfig.allSelection = []
        this.searchHandle()
      })
    },
      //流程状态样式显示
      bpmn_stateHandle(h, row) {
        // console.log('流程状态样row', row.bpmnState);
        return h('span',
            {
              class: {
                pass: row.bpmnState == 3||row.bpmnState == 10,
                warning: row.bpmnState == 1||row.bpmnState == 2||row.bpmnState == 4,
                fail: row.bpmnState == 0
              }
            },
            [
              h('span',
                  {
                    class: 'circle'
                  }
              ),
              row.taskName?row.taskName:row.bpmnStateStr
            ]
        )
      },
    historyRecord(row, path) {
      new this.$pageDrawer(
        historyList,
        {
          props: {
            row: row,
            path: path
          }
        },
/*        data => {
          data && this.search();
        }*/
      );
    },
    showUploading() {
      this.$Spin.show({
        render: h => {
          return h("div", [
            h("Icon", {
              class: "demo-spin-icon-load",
              props: {
                type: "ios-loading",
                size: 18
              }
            }),
            h("div", "上传中")
          ]);
        }
      });
    }
  },
  watch: {
    searchData: {
      handler(val) {
        this.formData = val
      },
      deep: true,
      immediate: true
    }
  }
};
